import React, {Component} from "react";
import {Button, Descriptions, Input, Modal, Table, Upload} from "antd";
import './style.css'
import {inject, observer} from "mobx-react";
import Text from "antd/es/typography/Text";

export default @inject('store') @observer
class UserManager extends Component {
    columns = [
        {
            title: 'ID',
            dataIndex: 'ID',
            key: 'ID'
        },
        {
            title: '用户名',
            dataIndex: 'username',
            key: 'username'
        },
        {
            title: '权限等级',
            dataIndex: 'authorization',
            key: 'authorization',
            render: (text) => (text === 0xff ? '管理员' : '用户')
        },
        {
            title: '头像',
            dataIndex: 'avatar',
            key: 'avatar',
            render: (text, item) => (this.avatar(text, item))
        },
        {
            title: '昵称',
            dataIndex: 'nickname',
            key: 'nickname'
        },
        {
            title: '手机号',
            dataIndex: 'phone',
            key: 'phone'
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (text, item) => (this.status(text, item))
        },
        {
            title: '操作',
            key: 'control',
            render: (item) => (
                <Button type={"primary"} onClick={() => this._openModal(item)}>修改</Button>
            )
        }
    ];

    limit = 6;

    constructor(props) {
        super(props);

        this.state = {
            data: [],
            selectedUser: null,
            current: 0,
            count: 0,
            modalOK: false,
            modalCancel: false,
            modalVisible: false,
            uploadVisible: false,
            imgUrl: '',
            item: {},
            password: '',
            nickname: '',
            phone: '',
        };
    }

    componentDidMount() {
        this.getUsers(0);
    }

    getUsers(offset) {
        window.$http.postForm("/user/gets", {
            offset: offset,
            limit: this.limit,
        }).then(res => {
            if (res.status === 10000) {
                this.setState({data: res.users, count: res.count});
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        })
    }

    avatar(text, item) {
        return <span>
            <img draggable={false} width={24} height={24} src={text} alt={'avatar'}/>
            <Button size={"small"}
                    className='avatar-button'
                    onClick={() => this.setState({uploadVisible: true, selectedUser: item})}
            >上传</Button>
        </span>

    }

    status(text, item) {
        switch (text) {
            case 0:
                return <span>
                    <Text type={"warning"}>未通过</Text>
                    <Button type={"primary"} size={"small"}
                            className='status-button'
                            onClick={() => this._setStatus(1, item.ID)}
                    >通过</Button>
                </span>;
            case 1:
                return <span>
                    <Text>正常ㅤ</Text>
                    <Button type={"danger"} size={"small"}
                            className='status-button'
                            onClick={() => this._setStatus(2, item.ID)}
                    >禁用</Button>
                </span>;
            case 2:
                return <span>
                    <Text type={"danger"}>已禁用</Text>
                    <Button type={"primary"} size={"small"}
                            className='status-button'
                            onClick={() => this._setStatus(1, item.ID)}
                    >恢复</Button>
                </span>;
            default:
        }
    }

    _setStatus(statusCode, userID) {
        window.$http.postForm("/user/changeStatus", {
                user_id: userID,
                status: statusCode,
            }).then(res => {
            if (res.status === 10000) {
                window.$message.success("success");
                this.getUsers((this.state.current - 1) * this.limit);
                return
            }
            window.$message.warn(res.message);
        }).catch(() => {
            window.$message.error('通讯失败');
        });
    }

    _openModal(item) {
        console.log(item);
        this.setState({
            item: item,
            password: '',
            nickname: item.nickname,
            phone: item.phone,
            modalVisible: true,
        });
    }

    _setUserData() {
        window.$http.postForm("/user/setData", {
                id: this.state.item.ID,
                password: this.state.password,
                nickname: this.state.nickname,
                phone: this.state.phone
            }
        ).then(res => {
            if (res.status === 10000) {
                window.$message.success("success");
                this.setState({modalVisible: false});
                this.getUsers((this.state.current - 1) * this.limit);
                return
            }
            window.$message.warn(res.message);
        }).catch(() => {
            window.$message.error('通讯失败');
        });
    }

    _uploadImg(info) {
        if (info.file.status !== 'uploading') {
            console.log(info.file, info.fileList);
            // return
        }


        switch (info.file.status) {
            case "done":
                window.$message.success(`${info.file.name} file uploaded successfully`);
                console.log(info);
                console.log("img url:", info.fileList[0].response);
                this.setState({imgUrl: info.fileList[0].response.url});
                break;
            case "error":
                window.$message.error(`${info.file.name} file upload failed.`);
                break;
            default:
        }
    }

    _setAvatar() {
        // todo: set Avatar url
        console.log('selectedUser', this.state.selectedUser);
        if (this.state.imgUrl !== '') {
            window.$http.postForm('/user/SetAvatar', {
                id: this.state.selectedUser.ID,
                avatar_url: this.state.imgUrl
            }).then(res => {
                if (res.status === 10000) {
                    window.$message.success("修改头像成功");
                    this.getUsers((this.state.current - 1) * this.limit);
                    return
                }

                window.$message.warn(res.message);
            }).catch(err => {
                window.$message.error(err.message);
            })
        } else {
            window.$message.warn('请先上传图片');
        }

        this.setState({uploadVisible: false});

    }


    render() {
        return (
            <div>
                <Table rowKey={record => record.id} pagination={{
                    total: this.state.count,
                    current: this.state.current,
                    pageSize: this.limit,
                    onChange: (page) => {
                        this.setState({current: page});
                        this.getUsers((page - 1) * this.limit);
                    }
                }}
                       columns={this.columns} dataSource={this.state.data}/>
                <Modal
                    closable={false}
                    onOk={() => this._setUserData()}
                    okText={'修改'}
                    onCancel={() => this.setState({modalVisible: false})}
                    visible={this.state.modalVisible}
                    item={this.state.item}
                    width={880}
                >
                    <Descriptions
                        title={'用户数据'}
                        bordered
                    >
                        <Descriptions.Item label={'ID'}>{this.state.item.ID}</Descriptions.Item>
                        <Descriptions.Item label={'用户名'}>{this.state.item.username}</Descriptions.Item>
                        <Descriptions.Item label={'密码'}>
                            <Input value={this.state.password} onChange={({target}) => {
                                this.setState({password: target.value});
                            }}/>
                        </Descriptions.Item>
                        <Descriptions.Item label={'权限等级'}>{this.state.item.authorization}</Descriptions.Item>
                        <Descriptions.Item label={'状态'}>{this.state.item.status}</Descriptions.Item>
                        <Descriptions.Item label={'昵称'}>
                            <Input value={this.state.nickname} onChange={({target}) => {
                                this.setState({nickname: target.value});
                            }}/>
                        </Descriptions.Item>
                        <Descriptions.Item label={'手机号'}>
                            <Input value={this.state.phone} onChange={({target}) => {
                                this.setState({phone: target.value});
                            }}/>
                        </Descriptions.Item>
                    </Descriptions>
                </Modal>
                <Modal
                    closable={false}
                    visible={this.state.uploadVisible}
                    onOk={() => this._setAvatar()}
                    onCancel={() => this.setState({uploadVisible: false})}
                >
                    <Upload
                        name={'avatar'}
                        action={'/upload/image'}
                        accept={'.png,.jpg'}
                        showUploadList={false}

                        onChange={(info) => this._uploadImg(info)}
                    >
                        {/*需要拿到上传后的url*/}
                        {this.state.imgUrl ?
                            <div><img src={this.state.imgUrl} width={300} height={300} alt="avatar"/></div>
                            : null}
                        <Button type={'upload'}> 上传图片 </Button>
                    </Upload>
                </Modal>
            </div>
        )
    }
}